import copy
import datetime
import importlib
import os
import threading
import json
import pathlib
import time


from absl import app, flags
from multiprocessing import Process

from coin2.service.order_detector.query_spec import get_exchange_detector_info
from coin2.service.order_detector.server import DetectorServer
from coin2.service.order_detector.common import QuerySpec

from concurrent.futures import ThreadPoolExecutor

def auto_update_run(key_root_path, update_time_sec):
  is_run = False
  while True:
    retry = 1
    while True:
      exchange_spce_list, ignore_list = get_exchange_detector_info(key_root_path)
      if len(exchange_spce_list) > 0:
        break
      else:
        print("get_exchange_detector_info error, retry size ", retry)
        retry += 1

    exchange_map = {}
    dump_map = {}
    for spce in exchange_spce_list:
      exchange = spce["exchange"]
      exchange_map.setdefault(exchange, [])
      exchange_map[exchange].append(spce)
      dump_map.setdefault(exchange, 0)
      dump_map[exchange] += 1

    dump_map["ignore_list"] = ignore_list
    dump_map["ignore_size"] = len(ignore_list)
    dump_map["exchange_info"] = exchange_map

    with open("./detecote_config.json", "w+") as f:
      json.dump(dump_map, f, indent=2)

    server_map = {}
    thread_list = []
    for name, spc_list in exchange_map.items():
      if name != "Binance":
        continue

      if name not in server_map:
        server_map[name] = DetectorServer(name)
      server_map[name].update_config(spc_list)

    if is_run == False:
      is_run = True
      for _, server in server_map.items():
        thread = threading.Thread(target=server.run)
        thread.start()
        thread_list.append(thread)

    time.sleep(update_time_sec)


def main(args):
  key_root_path = flags.FLAGS.key_root_path
  update_time = flags.FLAGS.update_time
  auto_update_run(key_root_path, update_time)

  
if __name__ == '__main__':
  flags.DEFINE_string(
      name="key_root_path", help="coin_key product path", default="/home/qiangluo/workspace/coin_key/view")
  flags.DEFINE_integer(
      name="update_time",
      help="interval for reload the config file",
      default=3000)
  app.run(main)
